package com.yoomiito.app.ui.anyview.goodsinfo.bottom

import android.content.Intent
import android.graphics.drawable.GradientDrawable
import android.text.TextUtils
import android.view.View
import android.widget.LinearLayout
import android.widget.Toast
import cn.droidlover.xdroidmvp.cache.SharedPref
import cn.droidlover.xdroidmvp.log.XLog
import cn.droidlover.xdroidmvp.net.ApiException
import cn.droidlover.xdroidmvp.net.ApiSubscriber
import cn.droidlover.xdroidmvp.net.BaseModel
import cn.droidlover.xdroidmvp.net.XApi
import com.google.gson.Gson
import com.yoomiito.app.Constant
import com.yoomiito.app.R
import com.yoomiito.app.base.App
import com.yoomiito.app.base.BaseActivity
import com.yoomiito.app.isEmptyOr0
import com.yoomiito.app.model.bean.AppInterfaceInfo
import com.yoomiito.app.model.bean.GoodsDetail
import com.yoomiito.app.net.YmApi
import com.yoomiito.app.ui.my.car.ShopCarActivity
import com.yoomiito.app.ui.my.instrument.InstrumentActivity
import com.yoomiito.app.ui.my.maintain.MaintainActivity
import com.yoomiito.app.ui.my.repurchase.RepurchaseActivity
import com.yoomiito.app.utils.AllCode
import com.yoomiito.app.utils.Const
import com.yoomiito.app.utils.DensityUtil
import com.yoomiito.app.utils.EventMessage
import com.yoomiito.app.utils.LoginUtils
import com.yoomiito.app.utils.LoginUtils.toOneKeyLogin
import com.yoomiito.app.utils.RouterUtils
import com.yoomiito.app.utils.Type
import com.yoomiito.app.utils.UserInfoConfig
import com.yoomiito.app.utils.YMToast
import com.yoomiito.app.widget.dialog.ShopCarDialog
import kotlinx.android.synthetic.main.view_goodsinfo_bottombar.view.goHome
import kotlinx.android.synthetic.main.view_goodsinfo_bottombar.view.goShopCar
import kotlinx.android.synthetic.main.view_goodsinfo_bottombar.view.leftBtn
import kotlinx.android.synthetic.main.view_goodsinfo_bottombar.view.leftBtnBottomTv
import kotlinx.android.synthetic.main.view_goodsinfo_bottombar.view.leftBtnTopTv
import kotlinx.android.synthetic.main.view_goodsinfo_bottombar.view.rightBtn
import kotlinx.android.synthetic.main.view_goodsinfo_bottombar.view.tv_card_num
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject
import java.io.IOException

class NewLiBaoBottomBar(context: BaseActivity<*>) :BaseBottomBar(context){

    override fun getLayoutId(): Int = R.layout.view_goodsinfo_bottombar

    override fun getParentView(): LinearLayout = this

    override fun initView(goodsDetail: GoodsDetail) {
        this.goodsDetail = goodsDetail;
        val drawable = leftBtn.background as GradientDrawable
        val radius = DensityUtil.dp2px(24f).toFloat()
        drawable.cornerRadius = radius
        val drawable1 = rightBtn.background as GradientDrawable
        drawable1.cornerRadius = radius
        goHome.setOnClickListener {
            RouterUtils.toMain(context,0)
        }
        if(goodsDetail.cartType == 100 || goodsDetail.cartType == 1 || goodsDetail.cartType == 2 || goodsDetail.cartType == 3){
//            goShopCar.visibility = VISIBLE
            leftBtnTopTv.text = "加入购物车"
        }else{
//            goShopCar.visibility = GONE
            leftBtnTopTv.text = "立即分享"
        }
        if(goodsDetail.cartNum == 0){
            tv_card_num.visibility = GONE
        }else{
            tv_card_num.visibility = VISIBLE
            tv_card_num.text = "" + goodsDetail.cartNum
        }
        goShopCar.setOnClickListener {
            if (App.mAppConfig.isLogin) {
                ShopCarActivity.start(context)
            } else {
//                        AllUtils.toLogin(YouPinGoodsActivity.this,AllCode.LoginIn);
                toOneKeyLogin(context)
            }
        }
        leftBtn.setOnClickListener {
            if(goodsDetail.cartType == 100){
                if (App.mAppConfig.isLogin) {
                    getInterface(goodsDetail.appInterface+"?productId="+ goodsDetail.id+ "&systemType=1")
                } else {
//                AllUtils.toLogin(context, AllCode.LoginIn)
                    LoginUtils.toOneKeyLogin(context)
                }
            }else if(goodsDetail.cartType == 1){
                context.startActivity(Intent(context, MaintainActivity::class.java))
            }else if(goodsDetail.cartType == 2){
                context.startActivity(Intent(context, InstrumentActivity::class.java))
            }else if(goodsDetail.cartType == 3){
                context.startActivity(Intent(context, RepurchaseActivity::class.java))
            }else{
                if (App.mAppConfig.isLogin){
                    showShareDialog()
                }else{
//                AllUtils.toLogin(context, AllCode.LoginIn)
                    LoginUtils.toOneKeyLogin(context)
                }
            }
        }

        rightBtn.setOnClickListener {
            if (App.mAppConfig.isLogin){
                onClick?.onClick(goodsDetail,Type.GoodsType.Gift)
            }else{
//                AllUtils.toLogin(context , AllCode.LoginIn)
                LoginUtils.toOneKeyLogin(context)
            }
        }
        val rule = !App.mAppConfig.isLogin || UserInfoConfig.getRoleId() <= Type.LevelType.VIP_7 || goodsDetail.get_money.isEmptyOr0()
        val vis = if (rule) View.GONE else View.VISIBLE
        leftBtnBottomTv.visibility = vis
//        val money = goodsDetail.get_money.removeDecimalPoint()
//        leftBtnBottomTv.text = "赚${money}元"
//        rightBtnBottomTv.visibility = vis
//        rightBtnBottomTv.text = "省${money}元"
//        leftBtnTopTv.text = if (rule) "分享" else "分享赚钱"
    }

    private fun addShopCar(num:Int,productId: String) {
        context.showLoading()
        YmApi.getYmService()
            .addShopCar(productId, num)
            .compose(context.bindToLifecycle())
            .compose(XApi.getApiTransformerNoData<BaseModel<*>>())
            .compose(XApi.getScheduler<BaseModel<*>>())
            .subscribe(object : ApiSubscriber<BaseModel<*>>() {
                override fun onSuccess(baseModel: BaseModel<*>) {
                    context.dismissLoading()
                    val eventMessage = EventMessage()
                    eventMessage.eventType = AllCode.NotifyShopCarData
                    EventBus.getDefault().postSticky(eventMessage)
                    onClickListener(ClickEvent(Const.Goods.ADD_SHOP_CAR,Type.GoodsType.BaoPin))
                    YMToast.showText("添加成功", Toast.LENGTH_SHORT)
                    goodsDetail?.cartNum = goodsDetail?.cartNum?.plus(num)
                    if(goodsDetail?.cartNum == 0){
                        tv_card_num.visibility = GONE
                    }else{
                        tv_card_num.visibility = VISIBLE
                        tv_card_num.text = "" + goodsDetail?.cartNum
                    }
                }

                override fun onFail(error: ApiException) {
                    context.dismissLoading()
                    if (!TextUtils.isEmpty(error.msg))
                        YMToast.showText(error.msg)
                }
            })

    }


    fun getInterface(url: String) {
        val client = OkHttpClient()
        val request = Request.Builder()
            .url(YmApi.BaseUrl + url)
            .addHeader(
                "Authorization",
                SharedPref.getInstance(App.getInstance()).getString(Constant.TOKEN, "")
            )
            .addHeader("Site", "app_mugwort_android")
            .header("Platform", "")
            .build()
        val call = client.newCall(request)
        XLog.e(YmApi.BaseUrl + url + "===")
        call.enqueue(object : Callback {
            // 2
            override fun onFailure(call: Call, e: IOException) {
                //Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                // 3
                try {
                    val obj = JSONObject(response.body()!!.string())
                    val data = obj.getString("data")
                    if (obj.getInt("code") == 200) {
                        val appInterfaceInfo = Gson().fromJson(
                            data,
                            AppInterfaceInfo::class.java
                        )
                        context.runOnUiThread{
                            if(shopCarDialog == null)
                                shopCarDialog = ShopCarDialog(context,appInterfaceInfo)
                            shopCarDialog?.show()
                            shopCarDialog?.setOnResultListener {num->
                                goodsDetail?.num_iid?.let { addShopCar(num, it) }
                            }
                        }


                    } else {

                    }
                    XLog.e("=======" + response.body()!!.string())
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        })
    }


}